package org.lzy.shop.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.checkbox.MaterialCheckBox
import com.google.android.material.imageview.ShapeableImageView
import com.google.android.material.textview.MaterialTextView
import org.lzy.shop.R
import org.lzy.shop.cart.CartItem
import org.lzy.shop.cart.ShoppingCartManager
import org.lzy.shop.util.setUrlRound

class CartAdapter(
    private var cartItems: List<CartItem>,
    private val onItemSelected: (Int, Boolean) -> Unit,
    private val onQuantityChanged: (Int, Int) -> Unit,
    private val onItemDeleted: (Int) -> Unit
) : RecyclerView.Adapter<CartAdapter.BrandGroupViewHolder>() {

    // 按品牌分组的数据
    private var groupedItems: List<ShoppingCartManager.CartItemGroup> = emptyList()
    // 用于在分组模式下查找原始位置
    private val itemPositionMap: MutableMap<Pair<Int, Int>, Int> = mutableMapOf() // (组索引, 组内索引) -> 原始位置

    init {
        updateData(cartItems)
    }

    // 更新数据并转换为分组形式
    fun updateData(newItems: List<CartItem>) {
        cartItems = newItems

        // 按品牌分组
        val grouped = newItems.groupBy { extractBrandName(it.goodsName) }
        groupedItems = grouped.map { (brandName, items) ->
            ShoppingCartManager.CartItemGroup(brandName = brandName, items = items)
        }

        // 构建位置映射
        itemPositionMap.clear()
        groupedItems.forEachIndexed { groupIndex, group ->
            group.items.forEachIndexed { itemIndex, item ->
                // 找到原始数据中的位置
                val originalPosition = cartItems.indexOfFirst { it.goodsId == item.goodsId && it.spec == item.spec }
                if (originalPosition != -1) {
                    itemPositionMap[Pair(groupIndex, itemIndex)] = originalPosition
                }
            }
        }

        notifyDataSetChanged()
    }

    // 删除商品项并添加动画
    fun deleteItemWithAnimation(originalPosition: Int) {
        // 查找对应的组和商品索引
        for ((key, value) in itemPositionMap) {
            if (value == originalPosition) {
                val (groupIndex, itemIndex) = key
                if (groupIndex < groupedItems.size && itemIndex < groupedItems[groupIndex].items.size) {
                    // 执行删除动画
                    val group = groupedItems[groupIndex]
                    val itemView = (holderMap[groupIndex]?.llBrandItems?.getChildAt(itemIndex)) ?: return

                    // 创建并执行动画
                    val animatorSet = android.animation.AnimatorSet()

                    // 平移动画 - 向左滑出
                    val translateX = android.animation.ObjectAnimator.ofFloat(
                        itemView,
                        "translationX",
                        0f,
                        -itemView.width.toFloat()
                    )

                    // 透明度动画 - 逐渐消失
                    val alpha = android.animation.ObjectAnimator.ofFloat(
                        itemView,
                        "alpha",
                        1f,
                        0f
                    )

                    // 组合动画
                    animatorSet.playTogether(translateX, alpha)
                    animatorSet.duration = 300 // 动画持续时间
                    animatorSet.start()

                    // 动画结束后更新数据
                    animatorSet.addListener(object : android.animation.Animator.AnimatorListener {
                        override fun onAnimationStart(animation: android.animation.Animator) {}

                        override fun onAnimationEnd(animation: android.animation.Animator) {
                            // 调用回调通知外部删除完成
                            onItemDeleted(originalPosition)

                            // 从列表中移除视图
                            holderMap[groupIndex]?.llBrandItems?.removeViewAt(itemIndex)

                            // 如果品牌组为空，也需要移除该组
                            if (holderMap[groupIndex]?.llBrandItems?.childCount == 0) {
                                // 从数据中移除该品牌组
                                val mutableGroupedItems = groupedItems.toMutableList()
                                mutableGroupedItems.removeAt(groupIndex)
                                groupedItems = mutableGroupedItems
                                notifyItemRemoved(groupIndex)

                                // 更新holderMap
                                holderMap.remove(groupIndex)
                            }

                            // 更新原始数据
                            val mutableCartItems = cartItems.toMutableList()
                            mutableCartItems.removeAt(originalPosition)
                            cartItems = mutableCartItems

                            // 重新构建位置映射
                            updatePositionMap()
                        }

                        override fun onAnimationCancel(animation: android.animation.Animator) {}

                        override fun onAnimationRepeat(animation: android.animation.Animator) {}
                    })

                    break
                }
            }
        }
    }

    // 保存ViewHolder引用的映射
    private val holderMap: MutableMap<Int, BrandGroupViewHolder> = mutableMapOf()

    // 更新位置映射
    private fun updatePositionMap() {
        itemPositionMap.clear()
        groupedItems.forEachIndexed { groupIndex, group ->
            group.items.forEachIndexed { itemIndex, item ->
                // 找到原始数据中的位置
                val originalPosition = cartItems.indexOfFirst { it.goodsId == item.goodsId && it.spec == item.spec }
                if (originalPosition != -1) {
                    itemPositionMap[Pair(groupIndex, itemIndex)] = originalPosition
                }
            }
        }
    }

    // 提取品牌名称
    private fun extractBrandName(goodsName: String): String {
        // 提取完整品牌型号（如第一张图中的"Redmi 14C"）
        val pattern = Regex("^([A-Za-z0-9]+\\s+[A-Za-z0-9]+)")
        val matchResult = pattern.find(goodsName)
        return matchResult?.value ?: run {
            // 如果不符合预期格式，回退到提取第一个单词
            val parts = goodsName.split(" ")
            if (parts.isNotEmpty()) parts[0] else "其他"
        }
    }

    // 获取原始数据位置
    fun getOriginalPosition(groupIndex: Int, itemIndex: Int): Int {
        return itemPositionMap[Pair(groupIndex, itemIndex)] ?: -1
    }

    // 获取当前要显示的项目总数（品牌组的数量）
    override fun getItemCount(): Int {
        return groupedItems.size
    }

    // 品牌组ViewHolder
    class BrandGroupViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val tvBrandName: MaterialTextView = itemView.findViewById(R.id.tv_brand_name)
        val llBrandItems: LinearLayout = itemView.findViewById(R.id.ll_brand_items)

    }

    // 商品项ViewHolder
    class CartItemViewHolder(itemView: View) {
        val cbSelect: MaterialCheckBox = itemView.findViewById(R.id.cb_item_select)
        val imgGoods: ShapeableImageView = itemView.findViewById(R.id.iv_item_image)
        val tvGoodsSpec: MaterialTextView = itemView.findViewById(R.id.tv_item_name)
        val tvGoodsPrice: MaterialTextView = itemView.findViewById(R.id.tv_item_price)
        val tvGoodsNum: MaterialTextView = itemView.findViewById(R.id.tv_item_quantity)
        val ivMinus: ShapeableImageView = itemView.findViewById(R.id.iv_minus)
        val ivAdd: ShapeableImageView = itemView.findViewById(R.id.iv_add)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BrandGroupViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_brand_title, parent, false)
        return BrandGroupViewHolder(view)
    }

    override fun onBindViewHolder(holder: BrandGroupViewHolder, position: Int) {
        val group = groupedItems[position]

        // 更新holderMap，确保始终持有最新的ViewHolder引用
        holderMap[position] = holder

        // 设置品牌名称
        holder.tvBrandName.text = group.brandName

        // 清空之前的商品项
        holder.llBrandItems.removeAllViews()



        // 为每个商品创建视图并添加到容器
        group.items.forEachIndexed { itemIndex, item ->
            val itemView = LayoutInflater.from(holder.itemView.context)
                .inflate(R.layout.item_cart, holder.llBrandItems, false)

            val itemViewHolder = CartItemViewHolder(itemView)

            // 设置商品数据
            setUrlRound(item.goodsMainPic, 50f, itemViewHolder.imgGoods)

            // 设置商品规格
            val specText = if (item.spec.isNotEmpty()) {
                item.spec.joinToString(" / ") { it.name ?: "" }
            } else {
                ""
            }
            itemViewHolder.tvGoodsSpec.text = specText

            // 设置商品价格
            val price = item.spec.firstOrNull()?.price ?: "0.00"
            itemViewHolder.tvGoodsPrice.text = "¥$price"

            // 设置商品数量
            itemViewHolder.tvGoodsNum.text = item.quantity.toString()

            // 设置选中状态
            itemViewHolder.cbSelect.isChecked = item.isSelected

            // 选中状态变化监听
            itemViewHolder.cbSelect.setOnCheckedChangeListener { _, isChecked ->
                val originalPosition = getOriginalPosition(position, itemIndex)
                if (originalPosition != -1) {
                    onItemSelected(originalPosition, isChecked)
                }
            }

            // 增加数量
            itemViewHolder.ivAdd.setOnClickListener {
                val newQuantity = item.quantity + 1
                val originalPosition = getOriginalPosition(position, itemIndex)
                if (originalPosition != -1) {
                    onQuantityChanged(originalPosition, newQuantity)
                }
            }

            // 减少数量
            itemViewHolder.ivMinus.setOnClickListener {
                if (item.quantity > 1) {
                    val newQuantity = item.quantity - 1
                    val originalPosition = getOriginalPosition(position, itemIndex)
                    if (originalPosition != -1) {
                        onQuantityChanged(originalPosition, newQuantity)
                    }
                }
            }

            // 添加到容器
            holder.llBrandItems.addView(itemView)


        }
    }

    // 更新单个商品的数量
    fun updateItemQuantity(originalPosition: Int, newQuantity: Int) {
        // 查找对应的组和商品索引
        for ((key, value) in itemPositionMap) {
            if (value == originalPosition) {
                val (groupIndex, itemIndex) = key
                if (groupIndex < groupedItems.size && itemIndex < groupedItems[groupIndex].items.size) {
                    // 转换为可变列表后更新数据
                    val mutableCartItems = cartItems.toMutableList()
                    mutableCartItems[originalPosition].quantity = newQuantity
                    cartItems = mutableCartItems

                    // 重新构建分组数据
                    updateData(cartItems)
                    notifyItemChanged(groupIndex)
                    break
                }
            }
        }
    }

    // 清理资源，防止内存泄漏
    fun clear() {
        holderMap.clear()
        itemPositionMap.clear()
    }
}


